package com.sjb.sixteen_journey_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sjb.sixteen_journey_backend.common.ImagesProperties;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.common.CommonHandle;
import com.sjb.sixteen_journey_backend.entity.Comment;
import com.sjb.sixteen_journey_backend.entity.Follower;
import com.sjb.sixteen_journey_backend.entity.ShareThing;
import com.sjb.sixteen_journey_backend.handler.exception.CustomException;
import com.sjb.sixteen_journey_backend.handler.exception.CustomExceptionCodeMsg;
import com.sjb.sixteen_journey_backend.mapper.FollowerMapper;
import com.sjb.sixteen_journey_backend.mapper.ShareThingMapper;
import com.sjb.sixteen_journey_backend.service.ICommentService;
import com.sjb.sixteen_journey_backend.service.IShareThingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 我的爆料表
 *
 * @author jcz
 * @since 2024-07-14
 */
@Service
public class ShareThingServiceImpl extends ServiceImpl<ShareThingMapper, ShareThing> implements IShareThingService {

    @Autowired
    private CommonHandle commonHandle;


    @Autowired
    private ShareThingMapper shareThingMapper;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private FollowerMapper followerMapper;

    @Autowired
    private ImagesProperties imagesProperties;
    @Override
//    public R addShareThing(ShareThing shareThing, ArrayList<MultipartFile> images) {
    public R addShareThing(ShareThing shareThing) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer id = (Integer) map.get("id");
            shareThing.setUserId(id);
            //储存图片到本地
//            List<String> files = commonHandle.saveImages(images, imagesProperties.getShareThing());
//            shareThing.setPath(files.toString());

            shareThing.setPath(shareThing.getImages().toString());
            boolean save = this.save(shareThing);
            if (save) {
//                Boolean b = commonHandle.addCommonness(images, id, 5, shareThing.getShareThingId(), "ShareThing");
//                if (b == false) {
//                    return R.error("添加爆料失败");
//                }
                return R.success(null, "添加爆料成功");
            }
            return R.error("添加爆料失败");
        } catch (Exception e) {
            throw new CustomException(CustomExceptionCodeMsg.SERVER_ERROR);
        }
    }

    @Override
    public R<List<ShareThing>> getAllShareThing() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            List<ShareThing> allShareThing = shareThingMapper.getAllShareThing(userId);
            if (allShareThing.size() > 0) {
                for (ShareThing s : allShareThing) {
                    List<String> strings = commonHandle.imageByStringToList(s.getPath());// 设置图片列表
                    s.setImages(strings);
                    //设置评论数量和当前用户对该用户是否关注
                    s = this.setCountAndFollow(s);
                }
                return R.success(allShareThing, "获取所有爆料成功");
            }
            return R.error("获取所有爆料失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<ShareThing> getShareThingById(Integer shareThingId, Boolean f) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            ShareThing allShareThingById = shareThingMapper.getAllShareThingById(shareThingId,userId);
            if (allShareThingById != null) {
                if (f) {
                    //每访问一下接口，其实浏览量就增加一次
                    UpdateWrapper<ShareThing> wrapper = Wrappers.update();
                    wrapper.set("pv", allShareThingById.getPv() + 1);
                    wrapper.eq("share_thing_id", shareThingId);
                    this.update(null, wrapper);
                    allShareThingById = shareThingMapper.getAllShareThingById(shareThingId,userId);
                }


                List<String> strings = commonHandle.imageByStringToList(allShareThingById.getPath());// 设置图片列表
                allShareThingById.setImages(strings);
                //设置评论数量和当前用户对该用户是否关注
                allShareThingById = this.setCountAndFollow(allShareThingById);

                return R.success(allShareThingById, "根据id获取爆料成功");
            }
            return R.error("无“爆料”");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R<List<ShareThing>> getAllMyTimeByUserId() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            List<ShareThing> shareThings = shareThingMapper.getAllShareThingByUserId(userId);
            for (ShareThing s : shareThings) {
                List<String> strings = commonHandle.imageByStringToList(s.getPath());// 设置图片列表
                s.setImages(strings);
                //设置评论数量和当前用户对该用户是否关注
                s = this.setCountAndFollow(s);
            }
            if (shareThings != null) {
                return R.success(shareThings, "获取到用户的我的时刻成功");
            }
            return R.error("获取我的时刻失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R deleteShareThingById(Integer id) {
        try {
            ShareThing myTime = this.getById(id);
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            if (userId.equals(myTime.getUserId())) {//判断是否是本人
                if (this.removeById(id)) {
                    if (commonHandle.deleteAssociationTable(myTime.getPath(), myTime.getStatus(), id, imagesProperties.getShareThing())) {
                        return R.success(null, "删除我的机票晒单成功");
                    }
                }
            }
            return R.error("删除我的机票晒单失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
@Override
    public ShareThing setCountAndFollow(ShareThing myTime) {
        Map<String, Object> map = ThreadLocalUtil.get();
        //我的此刻的评论数量
        QueryWrapper<Comment> query = Wrappers.query();
        query.eq("module_status",myTime.getStatus());
        query.eq("module_id", myTime.getShareThingId());
        long count = commentService.count(query);
        myTime.setCommentCount(count);

        Follower follower = new Follower();
        if(map!=null){
            Integer userId = (Integer) map.get("id");
            //当前用户对该用户是否关注
            QueryWrapper<Follower> followerQueryWrapper = Wrappers.query();
            followerQueryWrapper.eq("user_id",userId);
            followerQueryWrapper.eq("fans_id", myTime.getUserId());
            follower = followerMapper.selectOne(followerQueryWrapper);
        }
        myTime.setIs_followedByUser(follower==null ? false :follower.getStatus());
        return myTime;
    }
}
